package com.my.service.impl;

import com.my.constant.AuthServerContant;
import com.my.domain.SysLoginUser;
import com.my.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author coderMy
 * @Date 2021/3/30
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //判断是前台人员还是后台人员
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String loginType = request.getHeader(AuthServerContant.LOGIN_TYPE);
        if (ObjectUtils.isEmpty(loginType)){
            loginType = AuthServerContant.SYS_USER;
        }
        //后台人员
        if (AuthServerContant.SYS_USER.equals(loginType)){

            SysLoginUser sysLoginUser = sysUserMapper.selectUserByUsername(s);

            //查询权限
            if (!ObjectUtils.isEmpty(sysLoginUser)){
                List<String> auths = sysUserMapper.selectAuthsByUserId(sysLoginUser.getUserId());
                sysLoginUser.setAuths(auths);
            }

            return sysLoginUser;
            //前台人员
        }else {
            return null;
        }
    }
}
